# 3. 欢乐的周末

3

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});

const input = [];
rl.on('line', (line) => {
    input.push(line);
});
rl.on('close', () => {
    const [m, n] = input.shift().split(' ').map(Number);
    const map = input.splice(0, m).map(row => row.split(' ').map(Number));
    const visited = Array.from({length: m}, () => Array.from({length: n}, Array(2).fill(false)));
    const persons = [];
    const targets = [];

    for(let i=0; i<m; i++) {
        for(let j=0; j<n; j++) {
            if(map[i][j] === 2) {
                persons.push([i, j]);
            } else if (map[i][j] === 3) {
                targets.push([i, j]);
            }
        }
    }

    const xiaohua = persons[0];
    const xiaowei = persons[1];
    let res = 0;
    for(const target of targets) {
        visited.forEach(row => row.forEach(cell => cell.fill(false)));
        if (dfs(xiaohua[0], xiaohua[1], target[0], target[1], map, visited, 0)) {
            visited.forEach(row => row.forEach(cell => cell.fill(false)));
            if(dfs(xiaowei[0], xiaowei[1], target[0], target[1], map, visited, 1)) {
                res++;
            }
        }
    }
    console.log(res);
})

function dfs(currX, currY, targetX, targetY, map, visited, person) {
    if (currX === targetX && currY === targetY) {
        return true;
    }

    const dirs = [[-1, 0], [1, 0], [0, -1], [0, 1]];

    for(const dir of dirs) {
        const nextX = currX + dir[0];
        const nextY = currY + dir[1];
        if (nextX < 0 || nextY < 0 || nextX>=map.length || nextY>=map[0].length || map[nextX][nextY] === 1 || visited[nextX][nextY][person]) {
            continue;
        }

        visited[nextX][nextY][person] = true;
        if (dfs(nextX, nextY, targetX, targetY, map, visited, person)) {
            return true;
        }
    }

    return false;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64